import {computed, defineComponent, h, onMounted, onUnmounted, ref, watch} from "vue";
import { Steps } from "~/src/components/Steps";
import { UserInfo } from "~/src/components/UserInfo";
import Style1080 from './1080.module.scss';
import Stylevedio from './vediotop.module.scss';
import { KEEP_VIDEO_TOP } from '~/src/config';
import {getMzjf, gh, jyjs, mzjfPay, quhao, zyyjPay,  qxjs} from "@/api/his";
import {closeLoading, showLoading} from "@/utils";
import smt from '@/assets/images/smt.jpg'
import router from "@/router";
import {useRoute} from "vue-router";
import {useBreadcrumbStore} from "@/store/modules/breadcrumb";
import {showMessage} from "@/utils/hooks";
import {ghStore} from "@/store/modules/yvyue";
import {tempStore} from "@/store/modules/temp";
import {ElButton} from "element-plus";
export default defineComponent({
    setup: function () {
        const Style = KEEP_VIDEO_TOP ? Stylevedio : Style1080;
        const breadcrumbStore =useBreadcrumbStore();
        const ghstore =ghStore ();//实例化pinia存储
        const tempstore = tempStore();
        let route = useRoute()
        const zje = ref('0')
        const zyyj = ref(route.query.zyyjAmount as string)
        const mzjf = ref(tempstore.yjsItemInfo?.zje as string)
        const qhje =ref(tempstore.jyjsItemInfo?.zje as string)//取号费
        const ghf = ref(ghstore.hy?.Price)
        if (zyyj.value){
            zje.value = zyyj.value
        }else if (mzjf.value){
            zje.value = mzjf.value
        }else if (ghf.value){
            zje.value = ghf.value
        }else if (qhje.value){
            zje.value = qhje.value
        }
        // 首页Title跳转类型
        const lx = breadcrumbStore.titlelx;
        const scanCode = ref(''); // 存储扫码结果值
        //支付处理状态（防止重复扫描/重复支付）
        const isProcessing = ref(false);
        async function Pay() {
                showLoading();
                switch (lx) {
                    case '门诊缴费':{
                        await jyjsfun();
                        const res = await mzjfPay({ids: JSON.stringify(tempstore.mzjfids)})
                        router.push({path:'jfcg'});
                    }break;
                    case '住院预交金':{
                        const res = await zyyjPay({zyyjAmount: zyyj.value})
                        router.push({path:'lqpt'});
                    }break;
                    case '挂号':{
                        await jyjsfun();
                        const res = await gh({hy:ghstore.hy, doctor: ghstore.doctor,ghtype:'0'})
                        router.push({path:'lqpt'});
                    }break;
                    case '取号':{
                        await jyjsfun();
                        let res = await quhao({id:tempstore.qh?.id, type:'true', orderNo:tempstore.jyjsItemInfo?.orderNo,});
                        router.push({path:'lqpt'});
                    }break;
                }
                isProcessing.value = false;
                closeLoading() ;
        }
        // 校验结算
        const jyjsfun = async () => {
            if (!scanCode.value) {
                showMessage('扫码失败，请重新扫描付款码', 'error');
                closeLoading();
                isProcessing.value = false;
                return;
            }
            //校验结算
            const jy = await jyjs({
                scanCode: scanCode.value,
                orderNo:tempstore.yjsItemInfo?.orderNo
            })
            tempstore.setjyjsItemInfo({
                zje:jy.rows.zje,
                ybje:jy.rows.ybje,
                zfje:jy.rows.zfje,
                lsh:jy.rows.lsh,
                orderNo:jy.rows.orderNo,
                paystatus:jy.rows.status,
            })
        }

        // 扫码事件处理函数
        const handleScannerEvent = (ev: any) => {
            // 先判断是否正在处理支付，是则直接忽略
            if (isProcessing.value) {
                showMessage('正在处理支付中，请稍后再扫', 'warning');
                return;
            }
            if(ev && ev.detail && ev.detail.Code){
                ev.detail.code = ev.detail.Code;
            }
            if(ev && ev.detail && ev.detail.text){
                ev.detail.code = ev.detail.text;
            }
            // 存储扫码结果，标记扫码成功
            scanCode.value = ev.detail.code;
            isProcessing.value = true;

            // 扫码成功后触发支付
            Pay();
        };

        onMounted(() => {
            document.addEventListener('scanner_event', handleScannerEvent);
            // 开发测试：手动模拟扫码事件（正式环境注释）
            setTimeout(() => {

                //手动复制到浏览器控制台粘贴执行，，手动模拟扫码事件
                // let event = new CustomEvent('scanner_event', {
                //     detail: { Code: "123" }
                // });
                // parent.window.document.dispatchEvent(event);

            }, 2000);
        });

        // 取消支付
        const cancelPay = async()=>{
            // 支付中不允许取消
            if (isProcessing.value) {
                showMessage('正在处理支付中，暂无法取消', 'warning');
                return;
            }
            showLoading()
                if (lx === '取号' || lx === '挂号'){
                    // 1. 取号取消结算
                    await qxjs({
                        orderNo: tempstore.jyjsItemInfo?.orderNo,
                    })
                }
                closeLoading()
            console.log('取消支付')
            router.push({path:'/HomePage'});
        }
        const text =()=>{
            switch (lx) {
                case '挂号':{
                    return [
                        <span>就诊日期：{ghstore.date?.rq}</span>,
                        <span>号源：{ghstore.hy?.HDNAME}</span>,
                        <span>就诊科室：{ghstore.ks?.KS_MC}</span>,
                        <span>就诊医生：{ghstore.doctor?.DOCTORNAME}</span>
                    ]
                }
                case '取号':{
                    return [
                        <span>就诊日期：{tempstore.qh?.JZRQ}</span>,
                        <span>号源：{tempstore.qh?.HDNAME}</span>,
                        <span>就诊科室：{tempstore.qh?.KSMC}</span>,
                        <span>就诊医生：{tempstore.qh?.YSMC}</span>
                    ]
                }
            }
        }

        return () => <>
            <div class={Style.top}>
                <UserInfo  onTimeout={cancelPay}></UserInfo>
                <Steps></Steps>
                <div class={Style.container_mar}>
                    <div class={Style.body}>
                        <div class={Style.content} >
                            <div class={Style.text_content}>
                                {text()}
                                <div class={Style.infoItem}>
                                    <span class={Style.infoLabel}>总金额：</span>
                                    <span class={Style.infoValue}>￥{zje.value || '0.00'}</span>
                                </div>
                                <div class={Style.infoItem}>
                                    <span class={Style.infoLabel}>医保支付：</span>
                                    <span class={Style.infoValue}>￥{tempstore.yjsItemInfo?.ybje || '0.00'}</span>
                                </div>
                                <div class={Style.infoItem}>
                                    <span class={Style.infoLabel}>待支付：</span>
                                    <span class={Style.infoValue}
                                          style={{color: '#ff4d4f'}}>￥{tempstore.yjsItemInfo?.zfje || '0.00'}</span>
                                </div>
                            </div>
                            <div style={{fontSize: "60px", color: "#0d0b0b", marginBottom: "20px",}}>
                                请按图示内容操作
                            </div>
                            <img src={smt} style={{width: '800px', height: 'auto'}}/>
                            <div style={{
                                fontSize: "35px",
                                fontWeight: "bold",
                                color: "#f80606",
                                marginTop: "20px"
                            }}>请出示“支付宝”或“微信”付款码
                            </div>
                            <ElButton class={Style.btnStyle_item} type="primary" onClick={() => cancelPay()}>取消</ElButton>
                        </div>
                    </div>
                </div>
            </div>
        </>;
    }
})
